﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Net;
using System.IO;
using OgilvyOne.IDAL;
using OgilvyOne.Model;
using OgilvyOne.DALFactory;
using OgilvyOne.Utility;

namespace OgilvyOne.BLL
{
    public class MemberInfoBll
    {

        public const string MEMBER_LOGIN_INFO = "MEMBER_LOGIN_INFO";
        public const string MEMBER_HSK_LOGIN_COOKIES = "haoshiku_LOGGED_USER";
        public const string MEMBER_LOGIN_COOKIES = "cofcouser";
        private const string COOKIES_DOMAIN = "cofco.com";

        public const string MEMBER_TYPE_HSK = "3";
        public const string MEMBER_TYPE_WOMAI = "2";
        public const string MEMBER_TYPE_COFCO = "1";
        /// <summary>
        /// 会员注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Reg(MemberInfoModel model)
        {
            model.LastLoginTime = DateTime.Now;
            model.State = CmsConstants.YES;
            model.RegTime = DateTime.Now;
            model.Ip = System.Web.HttpContext.Current.Request.UserHostAddress;
            if (model.Password != null && model.Password != "")
            {
                model.Password = GetMD5(model.Password);
            }
            int mid= MemberInfoFactory.create().Add(model);
            if (mid > 0)
            {
                model.Memberid = mid;
                SetLoginValue(model);
                return true;
            }
            return false;
        }
        
        public static String GetMD5(string input)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            return s.ToString();
        }

        public void SetLoginValue(MemberInfoModel model)
        {
            DateTime now = DateTime.Now;
            MemberInfoFactory.create().UpdateLastLoginTime(model.Memberid, now);
            model.LastLoginTime = now;
            System.Web.HttpContext.Current.Session.Add(MEMBER_LOGIN_INFO, model); //登录
            if (model.UserType == "1")
            {
                HttpCookie Cookie = new HttpCookie(MEMBER_LOGIN_COOKIES);
                Cookie.Expires = DateTime.Now.AddMinutes(30);
                Cookie.Values["nickname"] = model.MemberNickname;
                Cookie.Values["ID"] = model.Memberid.ToString();
                Cookie.Values["type"] = model.UserType;
                Cookie.Domain = COOKIES_DOMAIN;
                Cookie.Path = "/";
                System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);

            }

            HttpCookie logincookie = new HttpCookie("idlasttime");
            logincookie.Expires = DateTime.Now.AddDays(1);
            byte[] bytes = Encoding.ASCII.GetBytes(model.Memberid + "," + now.Ticks);
            logincookie.Value = Convert.ToBase64String(bytes);
            System.Web.HttpContext.Current.Response.Cookies.Add(logincookie);
            
        }
        /// <summary>
        /// 当前登录会员信息
        /// </summary>
        /// <returns></returns>
        public MemberInfoModel GetLoginMemberInfo()
        {
            MemberInfoModel model = (MemberInfoModel)System.Web.HttpContext.Current.Session[MEMBER_LOGIN_INFO];
            if (model == null)
            {
                HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies[MEMBER_LOGIN_COOKIES];
                if (Cookie != null )
                {
                    try
                    {
                        model = GetMemberInfoModel(int.Parse(Cookie.Values["ID"]));
                        if (model != null)
                        {
                            if (model.State != CmsConstants.YES)
                            {
                                model = null;
                            }
                            else
                            {
                                System.Web.HttpContext.Current.Session.Add(MEMBER_LOGIN_INFO, model);
                            }
                        }
                    }
                    catch { }
                }

            }
            /*  if (model == null)
              {//好食库登录判断
                  HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies[MEMBER_HSK_LOGIN_COOKIES];
                  if (Cookie != null && Cookie.Value != null)
                  {
                      try
                      {
                          byte[] base64uid = new Base64Decoder().GetDecoded(Cookie.Value.Replace("%3D",""));
                          string uid = Encoding.Default.GetString(base64uid);
                          model = GetMemberInfoModel(uid, MEMBER_TYPE_HSK);
                          if (model == null)
                          {
                              model = new MemberInfoModel();
                              model.Username = uid;
                              model.MemberNickname = uid;
                              model.UserType = MEMBER_TYPE_HSK;
                              model.Password = "";
                              Reg(model);
                          }
                          else// (model != null)
                          {
                              if (model.State != CmsConstants.YES)
                              {
                                  model = null;
                              }
                              else
                              {
                                  SetLoginValue(model);
                              }
                          }
                      }
                      catch {
                       
                      }
                  } 
              }*/
            return model;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool Login(string username, string password)
        {
            return Login(username, password, "1");//官网登录
        }
        /// <summary>
        /// 退出
        /// </summary>
        public void Logout()
        {
            
            System.Web.HttpContext.Current.Session.RemoveAll();

            HttpCookie Cookie = new HttpCookie(MEMBER_LOGIN_COOKIES);
            Cookie.Expires = DateTime.Now.AddDays(-1);
            Cookie.Domain = COOKIES_DOMAIN;
            System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);

            HttpCookie Cookie2 = new HttpCookie("idlasttime");
            Cookie2.Expires = DateTime.Now.AddDays(-1);
            System.Web.HttpContext.Current.Response.Cookies.Add(Cookie2);

            /*HttpCookie hCookie = new HttpCookie(MEMBER_HSK_LOGIN_COOKIES);
            hCookie.Expires = DateTime.Now.AddDays(-1);
            hCookie.Domain = COOKIES_DOMAIN;
            System.Web.HttpContext.Current.Response.Cookies.Add(hCookie); */
            
        }


       

        public bool Login(string username, string password, string usertype)
        {
            MemberInfoModel mm = GetMemberInfoModel(username, usertype);
            if (mm != null)
            {
                if (mm.State == CmsConstants.YES)
                {//正常
                    if (mm.Password == GetMD5(password))
                    {
                        //System.Web.HttpContext.Current.Session.Add(MEMBER_LOGIN_INFO, mm);
                        SetLoginValue(mm);
                        
                        return true;
                    }
                }
            }
            return false;
        }
        /// <summary>
        /// 修改基本资料
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Update(MemberInfoModel model)
        {
            return MemberInfoFactory.create().Update(model);
        }
        /// <summary>
        /// 根据用户邮箱获取用户信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public MemberInfoModel GetMemberInfoModelEmail(string email)
        {
            return MemberInfoFactory.create().GetMemberInfoModelEmail(email);
        }
       /// <summary>
        /// 查询收藏列表
        /// </summary>
        /// <returns></returns>
        public IList GetColl(int mid,int top)
        {
            return MemberInfoFactory.create().GetColl(mid,top);  
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="mid"></param>
        /// <param name="newpas"></param>
        /// <returns></returns>
        public bool UpdatePassword(int mid, string newpas)
        {
            return MemberInfoFactory.create().UpdatePassword(mid, GetMD5(newpas));
        }
        /// <summary>
        /// 获得用户信息
        /// </summary>
        /// <param name="username"></param>
        /// <param name="userType">合作网站类型</param>
        /// <returns></returns>
        public MemberInfoModel GetMemberInfoModel(string username, string userType)
        {
            return MemberInfoFactory.create().GetMemberInfoModel(username, userType);
        }
        /// <summary>
        /// 获得用户信息
        /// </summary>
        /// <param name="username"></param>
        /// <param name="userType"></param>
        /// <returns></returns>
        public MemberInfoModel GetMemberInfoModel(string username)
        {
            return MemberInfoFactory.create().GetMemberInfoModel(username);
        }
        /// <summary>
        /// 用户名是否存在
        /// </summary>
        /// <param name="username"></param>
        /// <param name="userType">合作网站类型</param>
        /// <returns></returns>
        public bool IsExists(string username, string userType)
        {
            return MemberInfoFactory.create().IsExists(username, userType);
        }
        /// <summary>
        /// 用户名是否存在
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public bool IsExists(string username)
        {
            return MemberInfoFactory.create().IsExists(username);
        }
        /// <summary>
        /// 删除会员及相关信息
        /// </summary>
        /// <returns></returns>
        public bool Delete(int memberid)
        {
            return MemberInfoFactory.create().Delete(memberid);
        }
        /// <summary>
        /// 查询会员
        /// </summary>
        /// <param name="q"></param>
        /// <returns></returns>
        public IList GetUserList(MemberInfoModel q)
        {
            return MemberInfoFactory.create().GetUserList(q);
        }

        public MemberInfoModel GetMemberInfoModel(int mid)
        {
            return MemberInfoFactory.create().GetMemberInfoModel(mid);
        }

        public bool UpdateState(int mid, int state)
        {
            return MemberInfoFactory.create().UpdateState(mid, state);
        }
         /// <summary>
        /// 查询留言列表
        /// </summary>
        /// <returns></returns>
        public IList GetComments(int mid,int top)
        {
            return MemberInfoFactory.create().GetComments(mid,top);
        }
         /// <summary>
        /// 查询收藏列表
        /// </summary>
        /// <returns></returns>
        public IList GetColl(int mid, string cid)
        {
            return MemberInfoFactory.create().GetColl(mid,cid);
        }
        /// <summary>
        /// 查询留言总数
        /// </summary>
        /// <returns></returns>
        public IList GetCount(int mid, string auditstate)
        {
            return MemberInfoFactory.create().GetCount(mid,auditstate);
        }
        /// <summary>
        /// 查询收藏总数
        /// </summary>
        /// <returns></returns>
        public IList GetcollCount(int mid)
        {
            return MemberInfoFactory.create().GetcollCount(mid);
        }

        public void SaveUserImg(int mid,string img)
        {
            MemberInfoFactory.create().UpdateUserImg(mid, img);
            MemberInfoModel model = GetLoginMemberInfo();
            model.Userimg = img;
            SetLoginValue(model);
        }

        public string[] GetCoupon(int mid)
        {
            return MemberInfoFactory.create().GetCoupon(mid);
        }

        public bool UpdateCopon(string mcode)
        {
            return MemberInfoFactory.create().UpdateCopon(mcode);
        }

        class Base64Decoder
        {
            char[] source;
            int length, length2, length3;
            int blockCount;
            int paddingCount;
            public static Base64Decoder Decoder = new Base64Decoder();

            public Base64Decoder()
            {
            }

            private void init(char[] input)
            {
                int temp = 0;
                source = input;
                length = input.Length;

                for (int x = 0; x < 2; x++)
                {
                    if (input[length - x - 1] == '=')
                        temp++;
                }
                paddingCount = temp;

                blockCount = length / 4;
                length2 = blockCount * 3;
            }

            public byte[] GetDecoded(string strInput)
            {
                //初始化
                init(strInput.ToCharArray());

                byte[] buffer = new byte[length];
                byte[] buffer2 = new byte[length2];

                for (int x = 0; x < length; x++)
                {
                    buffer[x] = char2sixbit(source[x]);
                }

                byte b, b1, b2, b3;
                byte temp1, temp2, temp3, temp4;

                for (int x = 0; x < blockCount; x++)
                {
                    temp1 = buffer[x * 4];
                    temp2 = buffer[x * 4 + 1];
                    temp3 = buffer[x * 4 + 2];
                    temp4 = buffer[x * 4 + 3];

                    b = (byte)(temp1 << 2);
                    b1 = (byte)((temp2 & 48) >> 4);
                    b1 += b;

                    b = (byte)((temp2 & 15) << 4);
                    b2 = (byte)((temp3 & 60) >> 2);
                    b2 += b;

                    b = (byte)((temp3 & 3) << 6);
                    b3 = temp4;
                    b3 += b;

                    buffer2[x * 3] = b1;
                    buffer2[x * 3 + 1] = b2;
                    buffer2[x * 3 + 2] = b3;
                }

                length3 = length2 - paddingCount;
                byte[] result = new byte[length3];

                for (int x = 0; x < length3; x++)
                {
                    result[x] = buffer2[x];
                }

                return result;
            }

            private byte char2sixbit(char c)
            {
                char[] lookupTable = new char[64]{  
                 'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
                 'O','P','Q','R','S','T','U','V','W','X','Y', 'Z',
                 'a','b','c','d','e','f','g','h','i','j','k','l','m','n',
                 'o','p','q','r','s','t','u','v','w','x','y','z',
                 '0','1','2','3','4','5','6','7','8','9','+','/'};
                if (c == '=')
                    return 0;
                else
                {
                    for (int x = 0; x < 64; x++)
                    {
                        if (lookupTable[x] == c)
                            return (byte)x;
                    }

                    return 0;
                }

            }
        }

    }
}
